﻿using System.Web;
using System;
using System.Reflection;
using System.Web.Script.Serialization;

namespace Db7.HttpHandlers
{
    public class Invoke : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var req = context.Request;
            string TypeString = req["T"];
            string Assembly = TypeString.Before(".");
            Type typ = Type.GetType(TypeString + ", " + Assembly, true);
            string data = req["D"];
            string MethodName = req["M"];
            string jsMethodName = MethodName;
            MethodInfo mi = typ.GetMethod(jsMethodName);
            if (mi == null)
            {
                jsMethodName = jsMethodName.ToServerSideQName();
                mi = typ.GetMethod(jsMethodName);
            }
            object obj = Activator.CreateInstance(typ);
            if (data != null)
            {
                var deserializer = new CompactJSONSerializer();
                deserializer.Deserialize(data, obj);
            }
            var parameters = new object[]{null};
            mi.Invoke(obj, parameters);
            var serializer = new CompactJSONSerializer();
            string serialized = serializer.Serialize(obj);
            //var serializer = new JavaScriptSerializer();
            //serializer.RegisterConverters(new JavaScriptConverter[] { new PropBinderSerializer() });
            var resp = context.Response;
            resp.ContentType = "text/json";
            resp.Write( serialized);
        }
    }
}
